package fightplan.diag;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import com.jgoodies.forms.builder.DefaultFormBuilder;
import com.jgoodies.forms.layout.FormLayout;

import fightplan.business.Tournament;
import fightplan.core.FPExceptionHandler;

@SuppressWarnings("serial")
public class TournamentOptionsDialog extends JDialog {
	private Tournament tournament;

	private JCheckBox cbChildren = new JCheckBox("Kinderturnier");
	private JTextField tPriceFighter = new JTextField();
	private JTextField tPriceTeam = new JTextField();

	public TournamentOptionsDialog(JFrame owner, Tournament tournament) {
		super(owner);
		this.tournament = tournament;
		setTitle("Turnier Optionen");

		cbChildren.setSelected(tournament.isChildren());
		tPriceFighter.setText("" + tournament.getPriceFighter());
		tPriceTeam.setText("" + tournament.getPriceTeam());

		getContentPane().setLayout(new BorderLayout());
		getContentPane().add(build(), BorderLayout.CENTER);
		getContentPane().add(buildActions(), BorderLayout.SOUTH);
	}

	private Component build() {
		FormLayout layout = new FormLayout("left:max(40dlu;p), 4dlu, max(120dlu;p):grow(1)");
		DefaultFormBuilder builder = new DefaultFormBuilder(layout);

		builder.setDefaultDialogBorder();

		builder.appendSeparator("Art");
		builder.append(cbChildren, 3);

		builder.appendSeparator("Preise");
		builder.append("Einzel", tPriceFighter);
		builder.append("Team", tPriceTeam);

		return builder.getContainer();
	}

	public Component buildActions() {
		JPanel panel = new JPanel(new FlowLayout(SwingConstants.RIGHT));
		panel.add(new JButton(new SaveAction()));
		panel.add(new JButton(new CancelAction()));
		return panel;
	}

	private class SaveAction extends AbstractAction {

		public SaveAction() {
			putValue(Action.NAME, "Speichern");
		}

		public void actionPerformed(ActionEvent e) {
			try {
				tournament.setChildren(cbChildren.isSelected());
				tournament.setPriceFighter(Integer.parseInt(tPriceFighter.getText()));
				tournament.setPriceTeam(Integer.parseInt(tPriceTeam.getText()));
				TournamentOptionsDialog.this.setVisible(false);
				TournamentOptionsDialog.this.dispose();
			} catch (Exception x) {
				FPExceptionHandler.instance().handle(x);
			}
		}

	}

	private class CancelAction extends AbstractAction {

		public CancelAction() {
			putValue(Action.NAME, "Abbrechen");
		}

		public void actionPerformed(ActionEvent e) {
			TournamentOptionsDialog.this.setVisible(false);
			TournamentOptionsDialog.this.dispose();
		}

	}

}
